package optional;

import java.util.function.Supplier;

/**
 * @Author: WangYongGan
 * @Date: 2021/11/2 10:46
 * @Description:
 */
public class Lazy< T> implements Supplier< T> {

    private final Supplier< ? extends T> supplier;

    // 利用 value 属性缓存 supplier 计算后的值
    private T value;

    private Lazy(Supplier< ? extends T> supplier) {
        this.supplier = supplier;
    }

    public static < T> Lazy< T> of(Supplier< ? extends T> supplier) {
        return new Lazy< >(supplier);
    }

    public T get() {
        if (value == null) {
            T newValue = supplier.get();

            if (newValue == null) {
                throw new IllegalStateException("Lazy value can not be null!");
            }
            value = newValue;
        }
        return value;
    }
}
